/*
 PureMVC AS3 Demo - Flex CafeTownsend
 Copyright (c) 2007-08 Michael Ramirez <michael.ramirez@puremvc.org>
 Parts Copyright (c) 2005-07 Adobe Systems, Inc. 
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.model
{
	import mx.collections.XMLListCollection;
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.Constants;
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.business.ChangeQuotationStatusDelegate;
	import vn.demand.dragon.model.business.LoadQuotationDetailsDelegate;
	import vn.demand.dragon.model.business.LoadQuotationsDelegate;
	import vn.demand.dragon.model.business.RemoveQuotationDelegate;
	import vn.demand.dragon.model.business.SaveQuotationDelegate;
	import vn.demand.dragon.model.business.SaveQuotationLinesDelegate;

    /**
     * A proxy for the Employee data
     */
    public class QuotationProxy extends Proxy implements IProxy, IResponder
    {
		public static const NAME:String = "QuotationProxy";

		private var qitems:XMLList;
		private var qitemsDP:XMLListCollection;
		private var quoteVO:XML;

		public function QuotationProxy ( proxyId:String, data:Object = null ) 
        {
            super ( proxyId, data );
            quoteVO = data as XML;
        }
		
		public function loadQuotations(o:Object = null):void
		{
			// create a worker who will go get some data
			// pass it a reference to this proxy so the delegate knows where to return the data
			var delegate : LoadQuotationsDelegate = new LoadQuotationsDelegate( this );
			// make the delegate do some work
			delegate.loadQuotationService(o);
		}
		
		public function remove(params:Object):void {
			var delegate:RemoveQuotationDelegate = new RemoveQuotationDelegate(
				function(rpcEvent : Object) {
					var success:Boolean = rpcEvent.result.success == 'true'; 
					if (success) {
						sendNotification(CommonCommand.DELETE_QUOTATION_SUCESSFUL, null);
					} else {
						sendNotification(CommonCommand.DELETE_QUOTATION_FAILED, String(rpcEvent.result.errors));
					}
				},
				function(rpcEvent : Object) {
					sendNotification(CommonCommand.DELETE_QUOTATION_FAILED, 'Some thing wrong...');
				});
			delegate.removeQuotation(params);
		}
		
		public function loadQuotationDetails(quotation_id:int):void {
			var delegate:LoadQuotationDetailsDelegate = new LoadQuotationDetailsDelegate(resultQuotationDetails, faultQuotationLines);
			delegate.loadQuotationService(quotation_id);
		}
		
		public function resultQuotationDetails(rcpEvent:Object):void {
			qitems = rcpEvent.result.lines.line;
			qitemsDP = new XMLListCollection(qitems);
			
			quoteVO = rcpEvent.result;
			sendNotification( MarketingApplicationFacade.LOAD_QUOTATION_DETAIL_SUCCESS, qitems, this.proxyName);
		}
		
		public function faultQuotationLines( rpcEvent : Object ) : void 
		{
			errorStatus = "Could Not Load Quotations Lines!";
			sendNotification( MarketingApplicationFacade.LOAD_QUOTATION_DETAIL_FAILED, null, this.proxyName);
			
		}
		
		// this is called when the delegate receives a result from the service
		public function result( rpcEvent : Object ) : void
		{
			
			// populate the employee list in the proxy with the results from the service call
			data = new XMLListCollection(rpcEvent.result.quotations.item);
			sendNotification( MarketingApplicationFacade.LOAD_QUOTATION_SUCCESS, null, this.proxyName);
		}
		
		// this is called when the delegate receives a fault from the service
		public function fault( rpcEvent : Object ) : void 
		{
			data = new XMLListCollection();
			qitems = new XMLList();
			qitemsDP = new XMLListCollection();
			// store an error message in the proxy
			// labels, alerts, etc can bind to this to notify the user of errors
			errorStatus = "Could Not Load Quotations List!";
			sendNotification( MarketingApplicationFacade.LOAD_QUOTATION_FAILED, null, this.proxyName );
			
		}
		
		public function get quotationListDP():XMLListCollection
		{
			return data as XMLListCollection;
		}
		
		public function get quotationLinesDP():XMLListCollection
		{
			return qitemsDP;
		}
	
		public function get quotationVO():XML
		{
			return quoteVO;
		}
		
		public function get quotationLines():XMLList {
			return qitems;
		}
		
		
		public function newQuotationLine():XML {
			var xml:XML = new XML("<line><qitem_quotation>" + quotationVO.quote_id  +   "</qitem_quotation></line>");
			RIALogger.debug(this, xml.toXMLString());
			return xml;
		}
		
		public function getSameServiceLines(item_id:int, qitem_id:int):XMLList {
			return quotationLines.(child('qitem_item') == item_id && child('qitem_id') != qitem_id);
		}
		
		public function saveQuotationLines():void {
			var xml:String = "<root>" + quotationLines.toXMLString() + "</root>";			
			var delegate:SaveQuotationLinesDelegate = new SaveQuotationLinesDelegate(resultSaveQItems, faultSaveQItems);
			delegate.saveQItems(xml);
		}
		
		public function saveQuotation(quote:Object):void {
			var delegate:SaveQuotationDelegate = new SaveQuotationDelegate(resultSaveQuotation, faultSaveQuotation);
			delegate.saveQuotation(quote);
		}
		
		public function resultSaveQuotation(rcpEvent:Object):void {
			var success:Boolean = rcpEvent.result.success == 'true'; 
			if (success) {
				sendNotification(MarketingApplicationFacade.QUOTATION_UPDATED, {'id': rcpEvent.result.quote_id, 'code': rcpEvent.result.quote_code}, getProxyName());
			} else {
				sendNotification(MarketingApplicationFacade.QUOTATION_UPDATE_FAILED, rcpEvent.result.errors, getProxyName());				
			}
		}
		
		public function faultSaveQuotation(rcpEvent:Object):void {
			errorStatus = "Something wrong when save quotation!";
			sendNotification(MarketingApplicationFacade.QUOTATION_UPDATE_FAILED, errorStatus, this.proxyName);
		}
		
		public function resultSaveQItems(rcpEvent:Object):void {
			var success:Boolean = rcpEvent.result.success == 'true'; 
			if (success) {
				sendNotification(MarketingApplicationFacade.QITEMS_UPDATED, null, this.getProxyName());
			} else {
				sendNotification(MarketingApplicationFacade.QITEMS_UPDATE_FAILED, rcpEvent.result.errors, this.getProxyName());				
			}
		}
		
		public function faultSaveQItems(rcpEvent:Object):void {
			errorStatus = "Something wrong when save quotation lines!";
			sendNotification(MarketingApplicationFacade.QITEMS_UPDATE_FAILED, errorStatus, this.proxyName);
		}
		
		public function removeQItem(selIndex:int):Object {
			return quotationLinesDP.removeItemAt(selIndex);
		}
		
		public function copyQItem(copyItem:Object, targetRow:int):Object {
			var item:XML = new XML(XML(copyItem).toXMLString());
			item['qitem_quotation'] = String(quotationVO.quote_id);
			item['qitem_id'] = '';
			if (targetRow == quotationLinesDP.length - 1) {
				quotationLinesDP.addItemAt(item, targetRow);
			} else {
				quotationLinesDP.setItemAt(item, targetRow);
			}
			return item;
		}
		
		public function activateQuotation(quote_id:int):void {
			var delegate:ChangeQuotationStatusDelegate = new ChangeQuotationStatusDelegate(resultActivateQuotation, faultActivateQuotation);
			delegate.changeStatus(quote_id, Constants.QUOTATION_ACTIVATED);
		}
		
		public function unActivateQuotation(quote_id:int):void {
			var delegate:ChangeQuotationStatusDelegate = new ChangeQuotationStatusDelegate(resultUnActivateQuotation, faultUnActivateQuotation);
			delegate.changeStatus(quote_id, Constants.QUOTATION_UN_ACTIVATED);
		}
		
		public function completeQuotation(quote_id:int):void {
			var delegate:ChangeQuotationStatusDelegate = new ChangeQuotationStatusDelegate(resultCompleteQuotation, faultCompleteQuotation);
			delegate.changeStatus(quote_id, Constants.QUOTATION_COMPLETED);
		}
		
		private function resultActivateQuotation(rcpEvent:Object):void {
			sendNotification(MarketingApplicationFacade.QUOTATION_ACTIVATED, null, this.proxyName);
		}
		
		private function faultActivateQuotation(rcpEvent:Object):void {
			errorStatus = "Failed to change quotation status to Active";
			sendNotification(MarketingApplicationFacade.QUOTATION_ACTIVATE_FAILED, errorStatus, this.proxyName);
		}
		
		private function resultUnActivateQuotation(rcpEvent:Object):void {
			sendNotification(MarketingApplicationFacade.QUOTATION_UN_ACTIVATED, null, this.proxyName);
		}
		
		private function faultUnActivateQuotation(rcpEvent:Object):void {
			errorStatus = "Failed to change quotation status to Active";
			sendNotification(MarketingApplicationFacade.QUOTATION_UN_ACTIVATE_FAILED, errorStatus, this.proxyName);
		}
		
		private function resultCompleteQuotation(rcpEvent:Object):void {
			sendNotification(MarketingApplicationFacade.QUOTATION_COMPLETED, null, this.proxyName);
		}
		
		private function faultCompleteQuotation(rcpEvent:Object):void {
			errorStatus = "Failed to change quotation status to Active";
			sendNotification(MarketingApplicationFacade.QUOTATION_COMPLETE_FAILED, errorStatus, this.proxyName);
		}
		
		public var errorStatus:String;

	}
}